
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Text;
 using System.Windows.Forms;
using LPV_POS;
using LPV_POS.mh_pos;
using CrystalDecisions.CrystalReports.Engine;
using LPV_POS.Baocao;
using System.IO;
public partial class frmPHIEU_XUAT : Form
{
    string ma = "";//PK_: giá trị này dc truyền từ bảng danh sách, trường hợp EDIT
    DataTable tbMainDS = new DataTable();
    DataTable tbMain = new DataTable();
    Boolean iloadform = false;
    string sMAKHO = "";//FK_

    #region"    frmPHIEU_XUAT"
    public frmPHIEU_XUAT()
    {
        InitializeComponent();
    }
    #endregion

    #region"    frmPHIEU_XUAT_Load"
    public void frmPHIEU_XUAT_Load(object sender, EventArgs e)
    {
        btnluu.Enabled = false;
        btnxoa.Enabled = false;
        this.showcombobox();
        this.showdataDS();
        iloadform = true;

    }
    #endregion

    #region"    các hàm load dữ liệu"
    #region"    showdata"
    void showdata()
    {
        txtDOCID.ReadOnly = true;

        thuvien othuvien = new thuvien();//lớp truy xuat du lieu 
        tbMain = othuvien.SP_SelectDataTable("sp_PHIEU_XUAT",
                           new string[] { "@flag", "@DOCID" },
                           new object[] { 4, ma });
        tbMain.TableName = "PHIEU_XUAT";
    }
    #endregion
    #region"    showdataDS"
    void showdataDS()
    {
        string[] param = new string[50];
        object[] value = new object[50];
        int ipos = 0;
        param[ipos] = "@flag";
        value[ipos++] = 4;
        param[ipos] = "@MAKHO";
        value[ipos++] = sMAKHO;
        param[ipos] = "@NAM";
        value[ipos++] = cboNam.Text;

        grdPHIEU_XUAT.AutoGenerateColumns = false;

        thuvien othuvien = new thuvien();//lớp truy xuat du lieu 
        tbMainDS = othuvien.SP_SelectDataTable("sp_PHIEU_XUAT", param, value);

        grdPHIEU_XUAT.DataSource = tbMainDS;
        grdPHIEU_XUAT.Refresh();
        //tbMainDS.TableName = "PHIEU_XUAT";
        //tbMainDS.WriteXmlSchema(@"D:\Project\LPV-POS\LPV-POS\bin\Debug\report\ds_PHIEU_XUAT.xsd");
    }
    #endregion
    #region"    showinfo"
    void showinfo(int i1edt2sch)
    {

        this.showdata();
        if (tbMain.Rows.Count == 0)
        {
            txtDOCID.Text = "";
            txtSOCT.Text = "";
            txtMADONDH.Text = "";
            dtpNGAYCT.Value = DateTime.Now;
            dtpNGAY_GIO_GIAO.Value = DateTime.Now;

            if (cboMAKHO.Enabled)
                cboMAKHO.SelectedIndex = 0;

            txtDON_VI_DAT_HANG_TEN.Text = "";
            txtDON_VI_DAT_HANG_DIACHI.Text = "";
            txtDON_VI_DAT_HANG_NGUOILIENLAC.Text = "";
            txtDON_VI_DAT_HANG_DIENTHOAI.Text = "";
            txtDON_VI_DAT_HANG_DAIDIEN_BANHANG.Text = "";
            txtNOI_NHAN_TEN.Text = "";
            txtNOI_NHAN_DIACHI.Text = "";
            txtNOI_NHAN_NGUOILIENLAC.Text = "";
            txtNOI_NHAN_DIENTHOAI.Text = "";
            numTONGTIEN.Value = 0;
            numVAT_PHANTRAM.Value = 0;
            nudVAT_TIEN.Value = 0;
            numTONGTIEN.Value = 0;

            txtGHICHU.Text = "";
            
            return;
        }
        txtDOCID.Text = tbMain.Rows[0]["DOCID"] + "";
        txtSOCT.Text = tbMain.Rows[0]["SOCT"] + "";
        txtMADONDH.Text = tbMain.Rows[0]["MADONDH"] + "";

        dtpNGAYCT.Text = tbMain.Rows[0]["NGAYCT"] + "";
        dtpNGAY_GIO_GIAO.Text = tbMain.Rows[0]["NGAY_GIO_GIAO"] + "";

        cboMAKHO.SelectedValue = tbMain.Rows[0]["MAKHO"];

        txtDON_VI_DAT_HANG_TEN.Text = tbMain.Rows[0]["DON_VI_DAT_HANG_TEN"] + "";
        txtDON_VI_DAT_HANG_DIACHI.Text = tbMain.Rows[0]["DON_VI_DAT_HANG_DIACHI"] + "";
        txtDON_VI_DAT_HANG_NGUOILIENLAC.Text = tbMain.Rows[0]["DON_VI_DAT_HANG_NGUOILIENLAC"] + "";
        txtDON_VI_DAT_HANG_DIENTHOAI.Text = tbMain.Rows[0]["DON_VI_DAT_HANG_DIENTHOAI"] + "";
        txtDON_VI_DAT_HANG_DAIDIEN_BANHANG.Text = tbMain.Rows[0]["DON_VI_DAT_HANG_DAIDIEN_BANHANG"] + "";
        txtNOI_NHAN_TEN.Text = tbMain.Rows[0]["NOI_NHAN_TEN"] + "";
        txtNOI_NHAN_DIACHI.Text = tbMain.Rows[0]["NOI_NHAN_DIACHI"] + "";
        txtNOI_NHAN_NGUOILIENLAC.Text = tbMain.Rows[0]["NOI_NHAN_NGUOILIENLAC"] + "";
        txtNOI_NHAN_DIENTHOAI.Text = tbMain.Rows[0]["NOI_NHAN_DIENTHOAI"] + "";
        numTONGTIEN.Value = decimal.Parse(string.Concat("0" + tbMain.Rows[0]["TONGTIEN"]).Replace("0-", "-"));

        numVAT_PHANTRAM.Value = decimal.Parse(string.Concat("0" + tbMain.Rows[0]["VAT_PHANTRAM"]).Replace("0-", "-"));
        nudVAT_TIEN.Value = decimal.Parse(string.Concat("0" + tbMain.Rows[0]["VAT_TIEN"]).Replace("0-", "-"));
        nudTHANHTIEN.Value = decimal.Parse(string.Concat("0" + tbMain.Rows[0]["THANHTIEN"]).Replace("0-", "-"));

        txtGHICHU.Text = tbMain.Rows[0]["GHICHU"] + "";

    }
    #endregion
    #region"    showcombobox"
    void showcombobox()
    {

        thuvien othuvien = new thuvien();

        DataTable tbDM_DM_NGUYENLIEU = othuvien.SP_SelectDataTable("sp_PHIEU_XUAT", new string[] { "@flag" }, new object[] { 5 });
        cboMAKHO.DataSource = tbDM_DM_NGUYENLIEU;
        cboMAKHO.SelectedIndex = 0;

        for (int i = Variable.ngay_gio_hienhanh.Year; i >= Variable.ngay_gio_hienhanh.Year - 10; i--)
            cboNam.Items.Add(i);
        cboNam.SelectedIndex = 0;
    }
    #endregion
    #endregion

    #region"    các sự kiện _Click của các nút THÊM - SỬA- TÌM KIẾM - THOÁT - tbpDanhSach"
    #region"    btnDSthem_Click"
    private void btnDSthem_Click(object sender, EventArgs e)
    {
        tbMain = tbMainDS.Copy();
        tbMain.Clear();
        ma = "-1";
        this.showinfo(1);
        this.setStatusButton(1);
    }

    #endregion
    #region"    btnDSthoat_Click"
    private void btnDSthoat_Click(object sender, EventArgs e)
    {
        if (MessageBox.Show("Bạn muốn thoát?", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.OK)
        {
            this.Dispose();
        }

    }
    #endregion

    #endregion

    #region"    các sự kiện _Click của các nút LƯU - XÓA - SỬA  "

    #region"    btnluu_Click"
    private void btnluu_Click(object sender, EventArgs e)
    {
        if (this.save() > 0)
        {
            sMAKHO = "";//FK_
            sMAKHO = "";//FK_
            sMAKHO = "";//FK_
            sMAKHO = "";//FK_
            sMAKHO = "";//FK_
            MessageBox.Show("Lưu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.showdataDS();
        }
    }

    #endregion
    #region"    save"
    int save()
    {
        int _iReasult = -1;
        if (this.ValidateSave())
        {
            thuvien othuvien = new thuvien();//lớp truy xuat du lieu

            _iReasult = othuvien.SP_Update("sp_PHIEU_XUAT",
                 new string[] { "@flag", "@DOCID", "@SOCT", "@MADONDH", "@NGAYCT", "@NGAY_GIO_GIAO", 
                                "@MAKHO", "@DON_VI_DAT_HANG_TEN", "@DON_VI_DAT_HANG_DIACHI", "@DON_VI_DAT_HANG_NGUOILIENLAC", 
                                "@DON_VI_DAT_HANG_DIENTHOAI", "@DON_VI_DAT_HANG_DAIDIEN_BANHANG", "@NOI_NHAN_TEN", 
                                "@NOI_NHAN_DIACHI", "@NOI_NHAN_NGUOILIENLAC", "@NOI_NHAN_DIENTHOAI", "@TONGTIEN", "@GHICHU",
                                "@VAT_PHANTRAM", "@VAT_TIEN", "@THANHTIEN"},
                 new object[] { 1, ma, txtSOCT.Text, txtMADONDH.Text, dtpNGAYCT.Value, dtpNGAY_GIO_GIAO.Value, 
                                cboMAKHO.SelectedValue, txtDON_VI_DAT_HANG_TEN.Text, txtDON_VI_DAT_HANG_DIACHI.Text, txtDON_VI_DAT_HANG_NGUOILIENLAC.Text, 
                                txtDON_VI_DAT_HANG_DIENTHOAI.Text, txtDON_VI_DAT_HANG_DAIDIEN_BANHANG.Text, txtNOI_NHAN_TEN.Text, 
                                txtNOI_NHAN_DIACHI.Text, txtNOI_NHAN_NGUOILIENLAC.Text, txtNOI_NHAN_DIENTHOAI.Text, numTONGTIEN.Value, txtGHICHU.Text,
                                numVAT_PHANTRAM.Value, nudVAT_TIEN.Value, nudTHANHTIEN.Value
                 });
        }
        return _iReasult;
    }

    #endregion
    #region"    ValidateSave"
    Boolean ValidateSave()
    {
        return true;
    }

    #endregion
    #region"    delete"
    int delete()
    {
        thuvien othuvien = new thuvien();//lớp truy xuat du lieu    
        int _iReasult = othuvien.SP_Update("sp_PHIEU_XUAT",
                                 new string[] { "@flag", "@DOCID" },
                                 new object[] { 3, ma, });
        return _iReasult;
    }

    #endregion
    #region"    btnxoa_Click"
    private void btnxoa_Click(object sender, EventArgs e)
    {
        if (MessageBox.Show("Bạn muốn xóa PHIẾU XUẤT này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
        {
            if (this.delete() > 0)
            {
                MessageBox.Show("Xóa PHIẾU XUẤT thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ma = "-1";
                sMAKHO = "";//FK_
                sMAKHO = "";//FK_
                sMAKHO = "";//FK_
                sMAKHO = "";//FK_
                sMAKHO = "";//FK_
                this.showdataDS();
                this.setStatusButton(4);
            }
        }
    }

    #endregion
    #region"    sự kiên chọn trên lưới -- tblDanhSach"

    #region"    grdPHIEU_XUAT_SelectionChanged"
    private void grdPHIEU_XUAT_SelectionChanged(object sender, EventArgs e)
    {

        if (iloadform && grdPHIEU_XUAT.CurrentRow != null)
        {
            if (grdPHIEU_XUAT.CurrentRow.Index >= 0)
            {
                iloadform = false;
                ma = "-1";
                string _iSTT = grdPHIEU_XUAT.Rows[grdPHIEU_XUAT.CurrentRow.Index].Cells[0].Value + "";
                DataRow[] _dr = tbMainDS.Select("STT='" + _iSTT + "'");
                if (_dr.Length > 0)
                {
                    ma = _dr[0]["DOCID"] + "";
                    this.setStatusButton(2);
                }
                this.showinfo(1);
                iloadform = true;
            }
        }
    }
    private void grdPHIEU_XUAT_DoubleClick(object sender, EventArgs e)
    {
        this.grdPHIEU_XUAT_SelectionChanged(null, null);
    }
    #endregion
    #endregion
    #region "    setStatusButton"
    void setStatusButton(int i1New2Edt3Sch4Del5Sav)
    {
        btnDSthem.Enabled = i1New2Edt3Sch4Del5Sav != 1;
        btnxoa.Enabled = (i1New2Edt3Sch4Del5Sav != 1 && i1New2Edt3Sch4Del5Sav != 4 && i1New2Edt3Sch4Del5Sav != 3);

        btnluu.Enabled = i1New2Edt3Sch4Del5Sav != 5;
    }
    #endregion


    #region"    grdPHIEU_XUAT_DataError"
    private void grdPHIEU_XUAT_DataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        string sError = e.Exception.Message;
    }
    #endregion
    #region"    grd_DataError"
    private void grd_DataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        string sError = e.Exception.Message;
    }
    #endregion


    #endregion

    #region "   mh_chu"
    private void button1_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Đơn vị đặt hàng", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtDON_VI_DAT_HANG_TEN.Text = sNoiDung;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Địa chỉ", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtDON_VI_DAT_HANG_DIACHI.Text = sNoiDung;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Người liên lạc", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtDON_VI_DAT_HANG_NGUOILIENLAC.Text = sNoiDung;
    }

    private void button4_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Điện thoại", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtDON_VI_DAT_HANG_DIENTHOAI.Text = sNoiDung;
    }

    private void button5_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Đại diện bán hàng", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtDON_VI_DAT_HANG_DAIDIEN_BANHANG.Text = sNoiDung;
    }

    private void button6_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Nơi nhận", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtNOI_NHAN_TEN.Text = sNoiDung;
    }

    private void button7_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Địa chỉ", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtNOI_NHAN_DIACHI.Text = sNoiDung;
    }

    private void button8_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Người liên lạc", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtNOI_NHAN_NGUOILIENLAC.Text = sNoiDung;
    }

    private void button9_Click(object sender, EventArgs e)
    {
        mh_chu frm_chu = new mh_chu();
        string sNoiDung = frm_chu.ShowForm("Điện thoại", "", 300, 300, false);
        if (frm_chu.DialogResult == DialogResult.OK)
            txtNOI_NHAN_DIENTHOAI.Text = sNoiDung;
    }
    #endregion

    private void cboNam_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (iloadform)
            this.showdataDS();
    }

    private void btnChiTiet_Click(object sender, EventArgs e)
    {
        if (ma != "" && ma != "-1" && ma != "0")
        {
            frmPHIEU_XUAT_CT frm = new frmPHIEU_XUAT_CT();
            frm.ma = ma;
            frm.ShowDialog();
            this.showdataDS();
        }
    }

    private void In_Click(object sender, EventArgs e)
    {
        if (tbMain != null)
            if (tbMain.Rows.Count > 0)
            {
                this.Cursor = Cursors.WaitCursor;
                DataTable tbMain_CT = new thuvien().SP_SelectDataTable("sp_PHIEU_XUAT_CT",
                                                                   new string[] { "@flag", "@DOCID", "@MAHH" },
                                                                   new object[] { 4, ma, "" });
                tbMain_CT.TableName = "PHIEU_XUAT_CT";

                ReportDocument rpt = new ReportDocument();
                string sRptPath = Application.StartupPath + "\\report\\rptPHIEU_XUAT_A5.rpt";
                rpt.Load(sRptPath, CrystalDecisions.Shared.OpenReportMethod.OpenReportByTempCopy);

                #region "   PrinterDefault"
                System.Drawing.Printing.PrinterSettings cls = new System.Drawing.Printing.PrinterSettings();
                string sPrinterDefault = cls.PrinterName;
                rpt.PrintOptions.PrinterName = sPrinterDefault;
                #endregion

                ////////////////////////////////////
                //DataSet ds = new DataSet();
                //ds.Tables.Add(tbMain.Copy());
                //ds.Tables.Add(tbMain_CT.Copy());
                //rpt.SetDataSource(ds);
                DataTable tbLogo = this.get_Logo();
                ////////////////////////////////////                
                string sthanhtien_chu = new cpublic().ChuyenSo_ThanhChu(tbMain.Rows[0]["THANHTIEN"] + "");
                rpt.DataDefinition.FormulaFields["thanhtien_chu"].Text = "'" + sthanhtien_chu + "'";
                System.Collections.ArrayList arl = new System.Collections.ArrayList();
                arl.Add(tbLogo);
                arl.Add(tbMain);
                arl.Add(tbMain_CT);
                rpt.SetDataSource(arl);
                ////////////////////////////////////
                rpt.Database.Tables[0].SetDataSource(tbLogo);
                rpt.Database.Tables[1].SetDataSource(tbMain);
                rpt.Database.Tables[2].SetDataSource(tbMain_CT);

                rpt.PrintToPrinter(1, true, 1, 100);
                
                this.Cursor = Cursors.Default;
                mh_View frm = new mh_View(rpt);
                frm.ShowDialog();

                rpt.Dispose();
                return;
            }
        MessageBox.Show("Chọn phiếu xuất cần in");
    }

    private void numVAT_PHANTRAM_EditValueChanged(object sender, EventArgs e)
    {
        if (iloadform)
        {
            nudVAT_TIEN.Value = numTONGTIEN.Value * numVAT_PHANTRAM.Value / 100;
            nudTHANHTIEN.Value = numTONGTIEN.Value + nudVAT_TIEN.Value;
        }
    }

    private DataTable get_Logo()
    {
        DataTable dt = new DataTable();
        DataRow row;
        dt.Columns.Add("Hinh", System.Type.GetType("System.Byte[]"));
        dt.Columns.Add("HinhDetail", System.Type.GetType("System.Byte[]"));
        row = dt.NewRow();

        //Create Filestream to read image
        FileStream fs;

        //Create variable BinaryReader to read bytes of image
        BinaryReader br;

        //Check exists of image

        if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "logo1.bmp"))
        {
            //open image in file stream
            fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "logo1.bmp", FileMode.Open);
        }
        else //if image not exists show image Nopoto.img
            return dt;

        br = new BinaryReader(fs);
        byte[] b = new byte[fs.Length];
        b = br.ReadBytes(Convert.ToInt32(fs.Length));
        row["Hinh"] = b;
        row["HinhDetail"] = b;
        dt.Rows.Add(row);
        fs.Dispose();
        dt.TableName = "dt_hinh";

        return dt;
    }
}